<template>
  <div class="input-container">
    <el-form ref="formRef" :model="formData" :rules="formRules" class="basic-info-form-content">
      <div class="box-container basic-form">
        <div class="flex justify-content-space-between align-center">
          <div class="sub-title">基本信息</div>
          <el-button type="primary" @click="submitForm">
            <img alt="" src="@/assets/static/提交.png" style="width: 15px;margin-right: 10px">
            <div>提交</div>
          </el-button>
        </div>
        <!-- 第一行 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="6">
            <el-form-item label="病人ID" prop="userId">
              <el-input v-model="formData.userId" clearable placeholder="请输入病人ID"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="formData.userName" clearable placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="formData.age" clearable placeholder="请输入年龄"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="联系方式" prop="userPhone">
              <el-input v-model="formData.userPhone" clearable placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>

          <!--          <el-col :span="6">-->
          <!--            <el-form-item label="出生日期" prop="dob">-->
          <!--              <el-date-picker v-model="formData.dob" clearable format="YYYY-MM-DD HH:mm:ss" placeholder="请选择出生日期" style="width: 100%" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio value="Male">男</el-radio>
                <el-radio value="Woman">女</el-radio>
                <el-radio value="Unknown">未知</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="是否新生儿" prop="isNoun">
              <el-radio-group v-model="formData.isNoun">
                <el-radio :value="true">是</el-radio>
                <el-radio :value="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 科室字段保留 -->
          <el-col :span="6">
            <el-form-item label="科室" prop="departMentId">
              <el-select v-model="formData.departMentId" clearable placeholder="请输入科室" style="width: 100%">
                <el-option v-for="item in selectList.departMentList" :key="item.id" :label="item.departMenName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="主治医师" prop="doctorName">
              <el-input v-model="formData.doctorName" clearable placeholder="请输入主治医师"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="住院号" prop="admNumber">
              <el-input v-model="formData.admNumber" clearable placeholder="请输入住院号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入院日期" prop="admTime">
              <el-date-picker v-model="formData.admTime" clearable format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择入院日期" style="width: 100%" type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出院日期" prop="outTime">
              <el-date-picker v-model="formData.outTime" clearable format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择出院日期" style="width: 100%" type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="医保类型" prop="bmiCode">
              <el-select v-model="formData.bmiCode" clearable placeholder="请选择医保类型">
                <el-option
                    v-for="item in selectList.socialSecurityTypeList"
                    :key="item.id"
                    :label="item.bmiInfoName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <!--        <el-row :gutter="20">-->
        <!--          <el-col :span="6">-->
        <!--            <el-form-item label="联系方式" prop="userPhone">-->
        <!--              <el-input v-model="formData.userPhone" clearable placeholder="请输入联系电话"/>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
      </div>

      <div class="box-container basic-form" style="margin-top: 20px">
        <div class="sub-title">诊断信息</div>
        <!-- 第一行 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="12">
            <el-form-item label="主要诊断编码 (ICD-10)" label-width="220px" prop="dRGCreateDRGICD10InfoVo.drgOrganizationKey">
              <el-select v-model="formData.dRGCreateDRGICD10InfoVo.drgOrganizationKey" :loading="drgICD10ListLoading"
                         :remote-method="drgICD10CodeListFun"
                         clearable
                         filterable
                         placeholder="请输入诊断编码"
                         remote @change="handleDiagnosisCodeChange">
                <el-option v-for="(item,index) in selectList.drgICD10List" :key="item.drgOrganizationKey"
                           :label="item.drgOrganizationKey" :value="item.drgOrganizationKey"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="主要诊断名称" label-width="220px" prop="dRGCreateDRGICD10InfoVo.drgOrganizationName">
              <el-select v-model="formData.dRGCreateDRGICD10InfoVo.drgOrganizationName"
                         :loading="drgICD10ListLoading"
                         :remote-method="drgICD10NameListFun"
                         clearable
                         filterable
                         placeholder="请输入诊断名称"
                         remote @change="handleDiagnosisNameChange">
                <el-option v-for="(item,index) in selectList.drgICD10List" :key="item.drgOrganizationKey"
                           :label="item.drgOrganizationName" :value="item.drgOrganizationName"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入院途径" label-width="220px">
              <el-select v-model="formData.dRGCreateDRGICD10InfoVo.admTypeId" clearable placeholder="请选择入院途径"
                         style="width: 100%">
                <el-option v-for="item in selectList.admissionTypeList" :key="item.id" :label="item.admTypeName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="入院病情" label-width="220px">
              <el-radio-group v-model="formData.dRGCreateDRGICD10InfoVo.admTypeCond">
                <el-radio :value="1">危</el-radio>
                <el-radio :value="2">急</el-radio>
                <el-radio :value="3">一般</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第四行 -->
        <div>
          <div class="flex align-center" style="margin-top: 10px;cursor: pointer;width: fit-content;padding-right: 40px"
               @click="addOtherDiagnosis">
            <img alt="" src="@/assets/static/add.png" style="width: 18px;height: 18px; margin-right: 5px">
            <div style="color: #1a8c7b">添加其他诊断</div>
          </div>
        </div>
        <!-- 其他诊断列表 -->
        <el-row v-for="(diagnosis, index) in formData.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems"
                :key="new Date().getTime()+(Math.random()*100000).toFixed(5)"
                :gutter="20"
                style="margin-top: 20px">
          <el-col :span="12">
            <el-form-item :label="'其他诊断编码(ICD-10)'" label-width="220px">
              <el-select v-model="diagnosis.diseaseKey"
                         :loading="diagnosisListLoading"
                         :remote-method="diagnosisCodeListFun"
                         clearable
                         filterable
                         placeholder="请输入其他诊断信息"
                         remote @change="(val) => handleOtherDiagnosisCodeChange(val, index)">
                <el-option v-for="(item,index) in selectList.diagnosisList" :key="item.diseaseKey"
                           :label="item.diseaseKey" :value="item.diseaseKey"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="'其他诊断名称'" label-width="220px">
              <el-select v-model="diagnosis.diseaseName"
                         :loading="diagnosisListLoading"
                         :remote-method="diagnosisNameListFun"
                         clearable
                         filterable
                         placeholder="请输入其他诊断名称" remote
                         @change="(val) => handleOtherDiagnosisNameChange(val, index)"
              >
                <el-option v-for="(item,index) in selectList.diagnosisList" :key="item.diseaseKey"
                           :label="item.diseaseName" :value="item.diseaseName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button circle icon="Delete" type="danger" @click="removeOtherDiagnosis(diagnosis)"></el-button>
          </el-col>

        </el-row>
        <!-- 第五行判定结果 -->
        <!--        <div  style="border: 1px solid #e2e2e2;border-radius: 10px;background-color: #f3f3f3;margin-top: 20px" class="padding-20">-->
        <!--          <div class="description-header flex align-center">-->
        <!--            <img src="@/assets/static/对.png" style="width: 18px;height: 18px; margin-right: 5px" alt="">-->
        <!--           <div>并发症说明判定结果</div>-->
        <!--          </div>-->
        <!--          <div class="description-container">-->
        <!--            <div class="complication-item flex align-center">-->
        <!--              <div class="complication-type">MCC</div>-->
        <!--              <div class="complication-code">J18.901</div>-->
        <!--              <div class="complication-name"> - 重症肺炎</div>-->
        <!--            </div>-->
        <!--            <div class="complication-item flex align-center">-->
        <!--              <div class="complication-type">CC</div>-->
        <!--              <div class="complication-code">J18.901</div>-->
        <!--              <div class="complication-name"> - 原发性高血压</div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--          <div class="description-header flex align-center justify-content-end" >-->
        <!--            <el-popover placement="top-start" title="并发症说明" effect="dark" :width="400" trigger="hover" content="诊断中包含 1 个重症并发症(MCC)和 1 个一般并发症(CC)，将对DRG分组结果产生影响。">-->
        <!--              <template #reference>-->
        <!--                <img src="@/assets/static/info.png" style="width: 20px;height: 20px; margin-right: 5px" alt="">-->
        <!--                <div>并发诊断说明</div>-->
        <!--              </template>-->
        <!--            </el-popover>-->
        <!--         </div>-->
        <!--        </div>-->
      </div>
      <div class="box-container basic-form" style="margin-top: 20px">
        <div class="sub-title">手术信息</div>
        <!-- 第一行 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="12">
            <el-form-item label="主要手术操作编码 (ICD-9-CM3)" label-width="220px"
                          prop="dRGCreateDRGICD9InfoVo.drgOrganizationKey">
              <el-select v-model="formData.dRGCreateDRGICD9InfoVo.drgOrganizationKey" :loading="drgICD19ListLoading"
                         :remote-method="drgICD19CodeListFun"
                         clearable
                         filterable
                         placeholder="请输入ICD-9-CM3编码"
                         remote @change="handleOperationCodeChange">
                <el-option v-for="(item,index) in selectList.drgICD19List" :key="item.drgOrganizationKey"
                           :label="item.drgOrganizationKey" :value="item.drgOrganizationKey"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主要手术操作名称" label-width="220px" prop="dRGCreateDRGICD9InfoVo.drgOrganizationName">
              <el-select v-model="formData.dRGCreateDRGICD9InfoVo.drgOrganizationName" :loading="drgICD19ListLoading"
                         :remote-method="drgICD19NameListFun"
                         clearable
                         filterable
                         placeholder="主要手术操作名称"
                         remote @change="handleOperationNameChange">
                <el-option v-for="(item,index) in selectList.drgICD19List" :key="item.drgOrganizationKey"
                           :label="item.drgOrganizationName" :value="item.drgOrganizationName"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="8">
            <el-form-item label="操作日期" label-width="220px" prop="dateTime">
              <el-date-picker v-model="formData.dRGCreateDRGICD9InfoVo.dateTime" clearable format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择操作日期" style="width: 100%" type="datetime"
                              :disabled="formData.dRGCreateDRGICD9InfoVo.drgOrganizationKey == 0"
                              value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手术级别" label-width="220px" prop="leveInfoId">
              <el-select v-model="formData.dRGCreateDRGICD9InfoVo.leveInfoId" clearable placeholder="请选择手术级别"
                         :disabled="formData.dRGCreateDRGICD9InfoVo.drgOrganizationKey == 0">
                <el-option v-for="item in selectList.surgicalLevelList" :key="item.id" :label="item.surgeryLeveName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="麻醉方式" label-width="220px" prop="anesInfoId">
              <el-select v-model="formData.dRGCreateDRGICD9InfoVo.anesInfoId" clearable placeholder="请选择麻醉方式"
                         :disabled="formData.dRGCreateDRGICD9InfoVo.drgOrganizationKey == 0">
                <el-option
                    v-for="item in selectList.anesthesiaMethodList"
                    :key="item.id"
                    :label="item.anesName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <div>
          <!--          <div class="other-operation-info">其他手术信息</div>-->
          <div class="flex align-center" style="margin-top: 10px;cursor: pointer;width: fit-content;padding-right: 40px"
               @click="addOtherSurgeries">
            <img alt="" src="@/assets/static/add.png" style="width: 18px;height: 18px; margin-right: 5px">
            <div style="color: #1a8c7b">添加其他手术</div>
          </div>
        </div>
        <!-- 其他手术列表 -->
        <el-row v-for="(surgeries, index) in formData.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems"
                :key="new Date().getTime()+(Math.random()*100000).toFixed(5)"
                :gutter="20"
                style="margin-top: 20px">

          <el-col :span="12">
            <el-form-item :label="'其他手术操作编码(ICD-9-CM3)'" label-width="220px">
              <el-select v-model="surgeries.diseaseKey" :loading="surgeryListLoading"
                         :remote-method="surgeryCodeListFun"
                         clearable
                         filterable
                         placeholder="请输入其他手术操作编码"
                         remote @change="(val) => handleOtherSurgeryCodeChange(val, index)">
                <el-option v-for="(item,index) in selectList.surgeryList" :key="item.diseaseKey"
                           :label="item.diseaseKey" :value="item.diseaseKey"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item :label="'其他手术操作名称'" label-width="220px">
              <el-select v-model="surgeries.diseaseName" :loading="surgeryListLoading"
                         :remote-method="surgeryNameListFun"
                         clearable
                         filterable
                         placeholder="请输入其他手术操作名称"
                         remote @change="(val) => handleOtherSurgeryNameChange(val, index)">
                <el-option v-for="(item,index) in selectList.surgeryList" :key="item.diseaseKey"
                           :label="item.diseaseName" :value="item.diseaseName"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-button circle icon="Delete" type="danger" @click="removeOtherSurgeries(surgeries)"></el-button>
          </el-col>
        </el-row>

      </div>
      <div class="box-container basic-form" style="margin-top: 20px">
        <div class="sub-title">特殊治疗信息</div>

        <div class="treatment-grid" style="margin-top: 20px">
          <div v-for="item in selectList.specialTreatmentList" :key="item.id" class="treatment-item">
            <img :src="getTreatmentIcon(item.espCode)" alt="" class="icon-container">
            <div class="content">
              <div class="main-text">{{ item.drgespOrganizationName }}</div>
              <div class="sub-text">{{ item.espDescribe }}</div>
            </div>
            <div class="switch-container">
              <el-switch v-model="formData.espCode" :active-value="item.espCode" :inactive-value="''"
                         active-color="#007AFF" inactive-color="#ccc" size="small"/>
            </div>
          </div>
        </div>
      </div>
      <div class="flex justify-content-end" style="margin-top: 20px">
        <el-form-item>
          <el-button type="primary" @click="submitForm">
            <img alt="" src="@/assets/static/提交.png" style="width: 15px;margin-right: 10px">
            <div>提交</div>
          </el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-dialog title="DRG分组信息提示" v-model="centerDialogVisible" width="50%"  :show-close="false">
      <div style="font-size: 14px;">
        <div style="margin: 10px 0">
          您当前录入的主要诊断(编码:11{{validResult.diagnosisDRGOrganizationKey}},名称:{{validResult.diagnosisDRGOrganizationName}})
          与主要手术(编码:{{validResult.surgeryDRGOrganizationKey}}，名称:{{validResult.surgeryDRGOrganizationName}})存在逻辑不匹配:</div>
        <div style="background-color: #FEFCEA;border-left: 4px solid #F3CE49;padding: 20px;">
          <div style="margin: 5px 0">1、核对主要诊断/手术编码是否录入错误 (是否属于同一MDC大组、亚目是否准确);</div>
          <div style="margin: 5px 0">2、确认是否遗漏更相关的主要手术 (如本次住院的核心治疗性手术);</div>
          <div style="margin: 5px 0">3、若临床确无其他手术,可选择"无手术操作" (如某些保守治疗的慢性病)。</div>
          <div style="margin-top: 10px">
            <el-alert title="继续提交可能导致DRG分组结果不正确，请谨慎操作！" type="error" show-icon></el-alert>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="goOnSubmitForm">继续提交</el-button>
          <el-button type="primary" @click="centerDialogVisible = false">返回修改</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import {ref} from 'vue';
import {Search, Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import DateUtils from "@/utils/utils.js";
import {useRouter, useRoute} from 'vue-router';
import debounce from 'lodash/debounce'
import {
  createDRGSurgery,
  createDRGUserDisease,
  getADMType,
  getAnes,
  getBMIType,
  getDiagnosisList,
  getDRGDepartMentList,
  getICD10DGList,
  getICD19DGList,
  getSpecialList,
  getSurgeryLeve,
  getSurgeryList, getUserDetail, updateDRGUserDisease
} from "@/api/drg/drg.js";
const validResult = ref({
  diagnosisDRGOrganizationKey: "",
  diagnosisDRGOrganizationName: "",
  surgeryDRGOrganizationKey: "",  // 手术信息
  surgeryDRGOrganizationName: ""  // 手术信息
});
const centerDialogVisible = ref(false);
const router = useRouter();
const route = useRoute();
const getTreatmentIcon = (espCode) => {
  const iconMap = {
    'ESP01': new URL('@/assets/static/器官移植.png', import.meta.url).href,
    'ESP02': new URL('@/assets/static/ECMO.png', import.meta.url).href,
    'ESP03': new URL('@/assets/static/呼吸机.png', import.meta.url).href,
    'ESP04': new URL('@/assets/static/HIV.png', import.meta.url).href,
    'ESP05': new URL('@/assets/static/严重创伤.png', import.meta.url).href,
    'ESP06': new URL('@/assets/static/再入院.png', import.meta.url).href,
  };
  return iconMap[espCode] || iconMap['ESP01'];
};
const selectList = ref({
  surgicalLevelList: [], // 手术级别
  anesthesiaMethodList: [], // 麻醉方式
  admissionTypeList: [], // 入院类型
  socialSecurityTypeList: [], // 社保类型
  drgICD10List: [], // 主要诊断信息
  drgICD19List: [], //主要手术信息
  diagnosisList: [], //其他诊断信息
  surgeryList: [], //其他手术信息
  specialTreatmentList: [], // 特殊治疗信息
  departMentList: [], // 科室信息列表
});
// 表单验证规则
const formRules = {
  userId: [{required: true, message: '请输入病人ID', trigger: 'blur'}],
  userName: [{required: true, message: '请输入病人姓名', trigger: 'blur'}],
  departMentId: [{required: true, message: '请选择科室', trigger: 'change'}],
  admNumber: [{required: true, message: '请输入住院号', trigger: 'blur'}],
  admTime: [{required: true, message: '请输入入院时间', trigger: 'change'}],
  'dRGCreateDRGICD10InfoVo.drgOrganizationKey': [{required: true, message: '请输入主要诊断编码', trigger: 'change'}],
  'dRGCreateDRGICD10InfoVo.drgOrganizationName': [{required: true, message: '请输入主要诊断名称', trigger: 'change'}],
  'dRGCreateDRGICD9InfoVo.drgOrganizationKey': [{required: true, message: '请输入主要手术操作编码', trigger: 'change'}],
  'dRGCreateDRGICD9InfoVo.drgOrganizationName': [{required: true, message: '请输入主要手术操作名称', trigger: 'change'}],
};
// 表单引用
const formRef = ref(null);
const formData = ref({
  userId: "",
  userName: " ",
  dob: "",
  userPhone: "",
  outTime: "",
  sex: "Male",
  isNoun: false,
  doctorName: "",
  espCode: "",
  departMentId: "", // 科室字段
  age: "",
  admNumber: "",
  admTime: "",
  bmiCode: "",
  dRGCreateDRGICD10InfoVo: {    // 主要诊断信息
    drgOrganizationKey: "", // 主要诊断DRG分组Key
    drgOrganizationName: "", // 主要诊断DRG分组名称
    drgOrganizationParentId: "", // 主要诊断父级key标识
    admTypeId: "", // 入院类型途径Id
    admTypeCond: 1, // 入院情况
    dRGCreateDRGICD10InfoItems: [
      {diseaseKey: '', diseaseName: '', diseaseTableName: ''},
    ]
  },
  dRGCreateDRGICD9InfoVo: {
    drgOrganizationKey: "",  // 主要手术主要DRG分组Key
    drgOrganizationName: "",  // 主要诊断DRG分组名称
    drgOrganizationParentId: "", // 主要诊断父级key标识
    dateTime: "",  // 操作时间
    leveInfoId: "",  // 手术等级Id
    anesInfoId: "",  // 麻醉方式Id
    drgCreateDRGICD9InfoItems: []
  },
});
const drgICD10ListLoading = ref(false);// 添加主要诊断相关状态
const diagnosisListLoading = ref(false);// 其他诊断相关状态
const drgICD19ListLoading = ref(false);// 添加主要手术相关状态
const surgeryListLoading = ref(false);// 添加其他手术相关状态
// 请求主要诊断编码数据
const drgICD10CodeListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD10ListLoading.value = true
    const result = await getICD10DGList({organizationName: "", organizationKey: query});
    selectList.value.drgICD10List = result.data.data;
    drgICD10ListLoading.value = false;
  } else {
//    ElMessage.warning('主要诊断Code不能为空!');
  }
}, 500)
// 请求主要诊断名称数据
const drgICD10NameListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD10ListLoading.value = true
    const result = await getICD10DGList({organizationName: query, organizationKey: ""});
    selectList.value.drgICD10List = result.data.data;
    drgICD10ListLoading.value = false;
  } else {
    //  ElMessage.warning('主要诊断Name不能为空!');
  }
}, 500)
//请求其他诊断数据
const diagnosisCodeListFun = debounce(async (query) => {
  if (query !== '') {
    diagnosisListLoading.value = true
    const result = await getDiagnosisList({drgType: 0, diseaseKey: query, diseaseName: ""}); // 其他诊断信息
    selectList.value.diagnosisList = result.data.data;
    diagnosisListLoading.value = false;
  } else {
    //  ElMessage.warning('其他诊断Code不能为空!');
  }
}, 500)
//请求其他诊断数据
const diagnosisNameListFun = debounce(async (query) => {
  if (query !== '') {
    diagnosisListLoading.value = true
    const result = await getDiagnosisList({drgType: 0, diseaseKey: "", diseaseName: query}); // 其他诊断信息
    selectList.value.diagnosisList = result.data.data;
    diagnosisListLoading.value = false;
  }
}, 500)
//请求主要手术数据
const drgICD19CodeListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD19ListLoading.value = true
    const result = await getICD19DGList({organizationName: "", organizationKey: query}); // 主要手术信息
    result.data.data.unshift({
      id: "00000000-0000-0000-0000-000000000000",
      drgOrganizationKey: "0",
      drgOrganizationName: "无手术操作",
      drgOrganizationParentId: "0",
      drgLeve: 0,
      creationTime: "2025-09-16 16:01:06",
      isDeleted: false,
      extraProperties: {},
      concurrencyStamp: ""
    });
    selectList.value.drgICD19List = result.data.data;
    console.log("主要手术信息: ", selectList.value.drgICD19List)
    drgICD19ListLoading.value = false;
  }
}, 500)
//请求主要手术数据
const drgICD19NameListFun = debounce(async (query) => {
  if (query !== '') {
    drgICD19ListLoading.value = true
    const result = await getICD19DGList({organizationName: query, organizationKey: ""}); // 主要手术信息
    result.data.data.unshift({
      id: "00000000-0000-0000-0000-000000000000",
      drgOrganizationKey: "0",
      drgOrganizationName: "无手术操作",
      drgOrganizationParentId: "0",
      drgLeve: 0,
      creationTime: "2025-09-16 16:01:06",
      isDeleted: false,
      extraProperties: {},
      concurrencyStamp: ""
    });
    selectList.value.drgICD19List = result.data.data;
    console.log("主要手术信息: ", selectList.value.drgICD19List)
    drgICD19ListLoading.value = false;
  }
}, 500)
// 请求其他手术数据
const surgeryCodeListFun = debounce(async (query) => {
  if (query !== '') {
    surgeryListLoading.value = true
    const result = await getSurgeryList({drgType: 1, diseaseKey: query, diseaseName: ""});  // 其他手术信息
    selectList.value.surgeryList = result.data.data;
    surgeryListLoading.value = false;
  }
}, 500)
// 请求其他手术数据
const surgeryNameListFun = debounce(async (query) => {
  if (query !== '') {
    surgeryListLoading.value = true
    const result = await getSurgeryList({drgType: 1, diseaseKey: "", diseaseName: query});  // 其他手术信息
    selectList.value.surgeryList = result.data.data;
    surgeryListLoading.value = false;
  }
}, 500)
// 添加其他诊断
const addOtherDiagnosis = () => {
  formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.push({
    diseaseKey: '',
    diseaseName: '',
    diseaseTableName: ''
  });
}
// 添加其他手术
const addOtherSurgeries = () => {
  formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.push({
    diseaseKey: '',
    diseaseName: '',
    diseaseTableName: ''
  });
}
const removeOtherDiagnosis = (item) => {
  const index = formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.indexOf(item);
  if (index !== -1 && formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.length >= 1) {
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.splice(index, 1)
  } else {
    ElMessage.warning('其他诊断已全部删除!'); // 删除其他诊断
  }
}
const removeOtherSurgeries = (item) => {
  const index = formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.indexOf(item);
  if (index !== -1 && formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.length >= 1) {
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.splice(index, 1)
  } else {
    ElMessage.warning('其他手术已全部删除!'); // 删除其他诊断
  }

  //drgCreateDRGICD9InfoItems.value.length > 0?drgCreateDRGICD9InfoItems.value.splice(index, 1):ElMessage.warning('其他手术已全部删除!'); // 删除其他手术
}
const getSelectList = async (userId) => {
  Promise.all([
    getSurgeryLeve(),
    getAnes(),
    getADMType(),
    getBMIType(),
    getICD10DGList(), // 主要诊断信息
    getICD19DGList(), // 主要手术信息
    getDiagnosisList({drgType: 0}),  // 其他诊断信息
    getSurgeryList({drgType: 1}),  // 其他手术信息
    getSpecialList(), //特殊治疗信息
    getDRGDepartMentList()
  ]).then(res => {
    if (Array.isArray(res) && res.length > 0) {
      selectList.value.surgicalLevelList = res[0].data.data;
      selectList.value.anesthesiaMethodList = res[1].data.data;
      selectList.value.admissionTypeList = res[2].data.data;
      selectList.value.socialSecurityTypeList = res[3].data.data;
      selectList.value.drgICD10List = res[4].data.data;
      res[5].data.data.unshift({
        id: "00000000-0000-0000-0000-000000000000",
        drgOrganizationKey: "0",
        drgOrganizationName: "无手术操作",
        drgOrganizationParentId: "0",
        drgLeve: 0,
        creationTime: "2025-09-16 16:01:06",
        isDeleted: false,
        extraProperties: {},
        concurrencyStamp: ""
      });
      selectList.value.drgICD19List = res[5].data.data;
      console.log("主要手术信息: ", selectList.value.drgICD19List)
      selectList.value.diagnosisList = res[6].data.data;
      selectList.value.surgeryList = res[7].data.data;
      selectList.value.specialTreatmentList = res[8].data.data;
      selectList.value.departMentList = res[9].data.data;
      updateData();
    }
  })
};

const createDRGSurgeryInfo = async (data) => {
  let result = await createDRGSurgery(data);
  return result
}


// 提交表单方法
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let requestData = {};
      let dRGCreateDRGICD10InfoVo = {
        drgOrganizationKey: formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationKey,
        drgOrganizationName: formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationName,
        drgOrganizationParentId: formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId
      };
      let dRGCreateDRGICD9InfoVo = {
        drgOrganizationKey:  formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationKey,
        drgOrganizationName: formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationName,
        drgOrganizationParentId:formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId
      }
      // 验证分组方法
      let result = await createDRGSurgeryInfo({dRGCreateDRGICD10InfoVo, dRGCreateDRGICD9InfoVo});
      if (result.status == 200 && result.data.code == 200){
        await goOnSubmitForm();
      }else if (result.status == 200 && result.data.code == 400){
        validResult.value = result.data.data;
        centerDialogVisible.value = true;
      }
    } else {
      ElMessage.error('请填写完整信息！');
    }
  });
};

// 继续提交
const goOnSubmitForm = async () => {
  centerDialogVisible.value = false;
  let requestData = {};
  if (!!formData.value.userGuid) {
    requestData = await updateDRGUserDisease(formData.value);
  } else {
    requestData = await createDRGUserDisease(formData.value);
  }
  if (requestData.status == 200 && requestData.data.code == 200) {
    ElMessage.success(!!formData.value.userGuid ? '信息修改成功!' : '信息录入成功!');
    setTimeout(() => {
      router.push({path: '/drg/display', query: {id: requestData.data.data}});
    }, 1000);
  } else {
    ElMessage.error(!!formData.value.userGuid ? '信息修改失败!' : '信息录入失败!');
  }
};


// 重置表单方法
const resetForm = () => {
  formRef.value.resetFields();
};
// 处理主要诊断编码变化
const handleDiagnosisCodeChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD10List.find(item => item.drgOrganizationKey === value);
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationName = selectedItem.drgOrganizationName;
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationName = "";
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = "";
  }

};
// 处理主要诊断名称变化
const handleDiagnosisNameChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD10List.find(item => item.drgOrganizationName === value);
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationKey = selectedItem.drgOrganizationKey;
      formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationKey = "";
    formData.value.dRGCreateDRGICD10InfoVo.drgOrganizationParentId = "";
  }
};
// 处理其他诊断编码变化
const handleOtherDiagnosisCodeChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.diagnosisList.find(item => item.diseaseKey === value);
    console.log("处理其他诊断编码变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseName = selectedItem.diseaseName;
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseName = "";
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = "";
  }
};
// 处理其他诊断名称变化
const handleOtherDiagnosisNameChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.diagnosisList.find(item => item.diseaseName === value);
    console.log("处理其他诊断名称变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseKey = selectedItem.diseaseKey;
      formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseKey = "";
    formData.value.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems[index].diseaseTableName = "";
  }
};
// 处理主要手术操作编码变化
const handleOperationCodeChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD19List.find(item => item.drgOrganizationKey == value);
    console.log("处理主要手术操作编码变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationName = selectedItem.drgOrganizationName;
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationName = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = "";
  }
};
// 处理主要手术操作名称变化
const handleOperationNameChange = (value) => {
  if (value) {
    const selectedItem = selectList.value.drgICD19List.find(item => item.drgOrganizationName == value);
    console.log("处理主要手术操作名称变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationKey = selectedItem.drgOrganizationKey;
      formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = selectedItem.drgOrganizationParentId;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationKey = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgOrganizationParentId = "";
  }
};
// 处理其他手术编码变化
const handleOtherSurgeryCodeChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.surgeryList.find(item => item.diseaseKey === value);
    console.log("处理其他手术编码变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseName = selectedItem.diseaseName;
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseName = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = "";
  }
};
// 处理其他手术名称变化
const handleOtherSurgeryNameChange = (value, index) => {
  if (value) {
    const selectedItem = selectList.value.surgeryList.find(item => item.diseaseName === value);
    console.log("处理其他手术名称变化: ", selectedItem)
    if (selectedItem) {
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseKey = selectedItem.diseaseKey;
      formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = selectedItem.diseaseTableName;
    }
  } else {
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseKey = "";
    formData.value.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems[index].diseaseTableName = "";
  }
};
// 获取分组信息
const updateData = async () => {
  if (!!route.query.id) {
    const result = await getUserDetail({guid: route.query.id});
    if (result.status == 200 && result.data.code == 200) {
      const {
        userId,
        userName,
        dob,
        userPhone,
        outTime,
        sex,
        isNoun,
        doctorName,
        espCode,
        age,
        admNumber,
        admTime,
        id
      } = result.data.data;
      const departMentId = result?.data?.data?.departMentInfo?.id;
      const bmiCode = result?.data?.data?.bmiInfo?.id;
      // 诊断信息
      const dRGCreateDRGICD10InfoVo = {
        drgOrganizationKey: result.data.data.dRGCreateDRGICD10InfoVo.drgOrganizationKey,
        drgOrganizationName: result.data.data.dRGCreateDRGICD10InfoVo.drgOrganizationName,
        drgOrganizationParentId: result.data.data.dRGCreateDRGICD10InfoVo.drgOrganizationParentId,
        admTypeId: result.data.data.dRGCreateDRGICD10InfoVo.admTypeId,
        admTypeCond: result.data.data.dRGCreateDRGICD10InfoVo.admTypeCond,
        dRGCreateDRGICD10InfoItems: result.data.data.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems
      };
      const dRGCreateDRGICD9InfoVo = {
        drgOrganizationKey: result.data.data.dRGCreateDRGICD9InfoVo.drgOrganizationKey,  // 主要手术主要DRG分组Key
        drgOrganizationName: result.data.data.dRGCreateDRGICD9InfoVo.drgOrganizationName,  // 主要诊断DRG分组名称
        drgOrganizationParentId: result.data.data.dRGCreateDRGICD9InfoVo.drgOrganizationParentId, // 主要诊断父级key标识
        dateTime: result.data.data.dRGCreateDRGICD9InfoVo.dateTime,  // 操作时间
        leveInfoId: result.data.data.dRGCreateDRGICD9InfoVo.leveInfoId,  // 手术等级Id
        anesInfoId: result.data.data.dRGCreateDRGICD9InfoVo.anesInfoId,  // 麻醉方式Id
        drgCreateDRGICD9InfoItems: result.data.data.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems
      };
      const requestData = {
        userGuid: id,
        userId,
        userName,
        dob,
        userPhone,
        outTime,
        sex,
        isNoun,
        doctorName,
        espCode,
        age,
        admNumber,
        admTime,
        departMentId,
        bmiCode,
        dRGCreateDRGICD10InfoVo,
        dRGCreateDRGICD9InfoVo
      }
      formData.value = requestData
    }
    console.log("拿到分组的信息: ", formData.value);
  } else {
    console.log("创建分组信息,不需要拉取接口分组结果。。。。。。")
  }
};

getSelectList();
</script>
<style lang='scss' scoped>
.input-container {
  padding: 0 20px;
  border-radius: 5px;
  margin-top: 20px;

  .box-container {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 5px;
  }

  .basic-form {
    .sub-title {
      border-left: 4px solid #00968F;
      padding-left: 10px;
      font-size: 18px;
      font-weight: bolder;
      color: #333333;
    }
  }

  .description-header {
    margin-bottom: 10px;
  }

  .description-container {
    .complication-item {
      padding: 5px 0;

      .complication-type {
        width: 80px;
      }

      .complication-code {
        background-color: #c3e8cf;
        text-align: center;
        border-radius: 5px;
        padding: 4px 5px;
        color: #68A197;
        font-size: 14px;
      }

      .complication-name {
        margin-left: 20px;
        text-align: center;
        color: #333333;
      }
    }
  }


  .treatment-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }

  .treatment-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px 20px;
    transition: all 0.2s ease;
  }

  .treatment-item:hover {
    background-color: #e6f7ff;
    transform: translateY(-1px);
  }

  .icon-container {
    width: 40px;
    height: 40px;
    margin-right: 12px;

  }

  .content {
    flex: 1;
  }

  .main-text {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }

  .sub-text {
    font-size: 14px;
    color: #666;
  }

  .switch-container {
    margin-left: 12px;
  }

}


</style>
